package com.easyj.admin.edu.controller;

import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import com.easyj.base.common.ajax.Result;
import com.easyj.base.common.export.ExpExcutor;
import com.easyj.base.common.export.ExpField;
import com.easyj.base.controller.BaseController;
import com.easyj.base.exception.EasyjException;
import com.easyj.base.exception.ValidateException;
import com.easyj.base.util.DateTimeUtil;
import com.easyj.base.common.page.Page;
import com.easyj.base.common.page.PageFilter;
import com.easyj.admin.activiti.vo.SimpleApproveVO;
import com.easyj.admin.db.model.SocialJob;
import com.easyj.admin.db.model.SocialJobQO;
import com.easyj.admin.edu.service.SocialJobService;
	/**
	* 社会任职
	*
	 */
	@RestController
	@RequestMapping(value = "/edu/socialjob")
	public class SocialJobController extends BaseController{

		@Autowired
		private  SocialJobService socialJobService;

		/**
		 * get
		 * @param id
		 * @return
		 */
	    @GetMapping("/{id}")
	    public Result get(@PathVariable("id") Long id) {
	        SocialJob entity = socialJobService.findById(id);
	        return Result.Success(entity);
	    }
	    
	    
	    @RequestMapping(value = "findCommentsById", method = RequestMethod.GET)
		public Result findCommentsById(@RequestParam(value = "id") Long id) {
			return Result.Success(socialJobService.findCommentsById(id));
			
		}
		
		/**
		* 新增申请
		 * @throws EasyjException 
		*/
		@PreAuthorize("hasPermission('socialJob','socialJob:apply')")
		@PostMapping(value = "apply")
		public Result apply(@RequestBody @Validated SocialJob entity,BindingResult validResult) throws EasyjException {
			
            if(validResult.hasErrors()) {
				throw new ValidateException("数据不符合要求！");
			} 			
			socialJobService.apply(entity);
			return Result.Success();
			
		}
		
		/**
		* 重新申请
		 * @throws EasyjException 
		*/
		@PreAuthorize("hasPermission('socialJob','socialJob:apply')")
		@PostMapping(value = "reApply")
		public Result reApply(@RequestBody @Validated SocialJob entity,BindingResult validResult) throws EasyjException {
            if(validResult.hasErrors()) {
				throw new ValidateException("数据不符合要求！");
			} 			
            socialJobService.reApply(entity);
			return Result.Success();
			
		}
		
		
		/**
		* 查询自己的申请
		* @param filter
		* @return
		 */

		@PostMapping(value = "findSelf")
		public Result findSelf(@RequestBody  SocialJobQO filter) {			
		   //set applicantId
		    filter.setApplicantId(this.getUserId());
			Page<SocialJob>  page =socialJobService.findPage(filter);
			return Result.Success(page);
			
		}
		
		
		
		/**
		* 修改自己的申请
		 * @throws EasyjException 
		*/
		@PutMapping
		public Result update(@RequestBody @Validated SocialJob entity,BindingResult validResult) throws EasyjException {
            if(validResult.hasErrors()) {
				throw new ValidateException("数据不符合要求！");
			}  			
			socialJobService.updateEntity(entity);
			return Result.Success();
			
		}
		
		
        /**
 		 *取消
         * @throws EasyjException 
 		*/
		@RequestMapping(value = "cancel", method = RequestMethod.GET)
 		public Result cancel(@RequestParam(value = "id") Long id) throws EasyjException{
 			socialJobService.cancel(id);
 			return Result.Success();
 			
 		}
 		
 		
		
		@PostMapping(value = "approve")
		public Result approve(@RequestBody @Validated SimpleApproveVO entity,BindingResult validResult) throws EasyjException {
            if(validResult.hasErrors()) {
				throw new ValidateException("数据不符合要求！");
			} 
            entity.setApproveUserId(this.getUserId());
            
			socialJobService.approve(entity);
			return Result.Success();
			
		}
		
		/**
		  * 审核
       * @throws EasyjException 
		 */
		@PostMapping(value = "auditApply")
		public Result auditApply(@RequestBody @Validated SimpleApproveVO entity,BindingResult validResult) throws EasyjException {
			
          if(validResult.hasErrors()) {
				throw new ValidateException("数据不符合要求！");
			} 
          entity.setApproveUserId(this.getUserId());
          
          socialJobService.auditApply(entity);
		  return Result.Success();
			
		}
		
		
 		
 		/**
		* 分页查询
		* @param filter
		* @return
		 */
		@PreAuthorize("hasPermission('socialJob','socialJob:list')")
		@PostMapping(value = "findPage")
		public Result findPage(@RequestBody  SocialJobQO filter) {			
		    if(filter.getPage().getLimit()>MaxLimit) {
				return Result.Error(10009,"超出一次读取最大行数"); 
			}
			Page<SocialJob>  page =socialJobService.findPage(filter);
			return Result.Success(page);
			
		}
		
		 /**
		* 导出Excel
		* @param filter
		* @param expFields
		* @param response
		*/
		@PreAuthorize("hasPermission('socialJob','socialJob:list')")
		@RequestMapping(value = "export", method = RequestMethod.POST)
		public void export(@RequestBody SocialJobQO filter, HttpServletResponse response){
			try {
				 //导出的字段		
				List<ExpField> fields = new ArrayList<ExpField>();
				fields.add(new ExpField("applyName","申请标题",""));
			      fields.add(new ExpField("applicantName","申请人"));
			      fields.add(new ExpField("appleyTime","申请时间","left","date"));
			      fields.add(new ExpField("deptName","所属部门"));
			      
			      fields.add(new ExpField("name","任职名称"));
			      fields.add(new ExpField("typeName","任职类型"));
			      fields.add(new ExpField("organizationt","任职单"));
			      fields.add(new ExpField("certifier","证明人"));
			      fields.add(new ExpField("startTime","开始时间","left","date"));
			      fields.add(new ExpField("endTime","结束时间","left","date"));
			      fields.add(new ExpField("jobContent","任职概况"));
			      
			      fields.add(new ExpField("statusName","审批结果"));
			      fields.add(new ExpField("approveComment","审批意见"));
			      fields.add(new ExpField("approveName","审批人"));
			      fields.add(new ExpField("approveTime","审批时间","left","date"));
			    
				//生成 excel
				SXSSFWorkbook workbook=exportExcel(filter, fields);
				response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); 
				String filename="社会任职"+DateTimeUtil.getDateStr8(new Date())+".xlsx";
				String newFileName=URLEncoder.encode(filename,"UTF-8");
				response.setHeader("Content-disposition", "attachment;filename=" + newFileName); 
				OutputStream ouputStream = response.getOutputStream();  
				workbook.write(ouputStream);  
				ouputStream.flush();  
				ouputStream.close();  
			} catch (Exception ex) {
				log.error("SocialJobController.export", ex);
			} 
		}
		
		/**
		* 导出excel,生成workbook 
		*/
		private SXSSFWorkbook exportExcel(final SocialJobQO filter,List<ExpField> fields) {
			ExpExcutor<SocialJob>  expExcutor=new ExpExcutor<SocialJob>(){
				@Override
				protected Long getRecordCount() {
					return socialJobService.count(filter);
				}

				@Override
				protected List<SocialJob> getSheetData(int sheetSize, int sheetinx) {
					PageFilter queryPage=new PageFilter(sheetSize,sheetinx+1);
					filter.setPage(queryPage);
					List<SocialJob> datas=null;
					datas = socialJobService.findList(filter);
					
					return datas;
				}
			};
			SXSSFWorkbook workbook=expExcutor.export(fields,false);
			return workbook;
		}	

}

